#--*--coding=utf-8--*--
#MaterialCodeGenerator6.py
#搜索框位置错误，没有复制按钮，搜索框输入后没有反应


import chardet

import sys
import json
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QLineEdit, QPushButton, QHBoxLayout, QLabel
from PySide6.QtCore import Qt

class MaterialCodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        #self.dropdownGroups = []
        self.load_rules_from_json('rules2.json')

    def initUI(self):
        self.layout = QVBoxLayout()

        # 初始化下拉列表组
        self.dropdownGroups = []
        self.labels = []

        # 搜索框
        self.searchBoxes = []

        # 增加和删除按钮
        buttonLayout = QHBoxLayout()
        self.copy_button = QPushButton("复制")
        addButton = QPushButton("增加", self)
        removeButton = QPushButton("删除", self)
        addButton.clicked.connect(self.addDropdownGroup)
        removeButton.clicked.connect(self.removeDropdownGroup)
        buttonLayout.addWidget(addButton)
        buttonLayout.addWidget(removeButton)

        # 结果标签
        self.resultLabel = QLabel("", self)
        self.layout.addWidget(self.resultLabel)

        self.layout.addLayout(buttonLayout)
        self.setLayout(self.layout)

#     def load_rules_from_json(self, file_path):
#         with open(file_path, 'r') as file:
#             self.rules = json.load(file)
            
# 加载规则
    def load_rules_from_json(self, file_path):
        # 读取文件内容以检测编码
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            encoding = result['encoding']
        
        # 使用检测到的编码打开文件并加载JSON数据
        with open(file_path, 'r', encoding=encoding) as file:
            self.rules = json.load(file)            
                
            

    def addDropdownGroup(self):
        group = [QComboBox(self) for _ in range(3)]
        searchBox = QLineEdit(self)
        label = QLabel("", self)

        for i, comboBox in enumerate(group):
            part = f"part{i+1}"
            comboBox.addItems(self.rules[part].keys())
            comboBox.currentIndexChanged.connect(self.updateResult)
            comboBox.setInsertPolicy(QComboBox.NoInsert)
            comboBox.setEditable(True)
            comboBox.lineEdit().setReadOnly(True)

        searchBox.textChanged.connect(lambda text, g=group: self.filterComboBoxes(text, g))
        self.dropdownGroups.append(group)
        self.searchBoxes.append(searchBox)
        self.labels.append(label)

        layout = QHBoxLayout()
        layout.addWidget(searchBox)
        for comboBox in group:
            layout.addWidget(comboBox)
        layout.addWidget(label)

        self.layout.insertLayout(self.layout.count() - 2, layout)

    def removeDropdownGroup(self):
        if self.dropdownGroups:
            group = self.dropdownGroups.pop()
            searchBox = self.searchBoxes.pop()
            label = self.labels.pop()
            for comboBox in group:
                comboBox.deleteLater()
            searchBox.deleteLater()
            label.deleteLater()
            self.updateResult()

    def filterComboBoxes(self, text, group):
        for comboBox in group:
            current_text = comboBox.currentText()
            comboBox.clear()
            items = [comboBox.itemText(i) for i in range(comboBox.count())]
            filtered_items = [item for item in items if text.lower() in item.lower()]
            comboBox.addItems(filtered_items)
            comboBox.setCurrentText(current_text)

    def updateResult(self):
        result = ""
        for group in self.dropdownGroups:
            #print("group:",group)
            #for comboBox in group:
                #print("comboBox:",comboBox)
                #parts = comboBox.currentText()
            parts = [comboBox.currentText() for comboBox in group]
            print("parts:",parts)
            if all(parts):
                result += ".".join(parts) + "."
        #输出是不正确的，需求是输出列表对应的值，而实际是输出的列表name,而且不能单独控制单下拉列表        
        self.resultLabel.setText(result.rstrip(".")) 
        
    def copy_code(self):
        code = self.code_label.text().split(': ')[1]
        clipboard = QApplication.clipboard()
        clipboard.setText(code)
        QMessageBox.information(self, "提示", "编码已复制到剪贴板！")
        
        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MaterialCodeGenerator()
    ex.show()
    sys.exit(app.exec())